use sea_orm::{
    ConnectOptions, Database as SeaDatabase, DatabaseConnection, DbErr,
};
use std::time::Duration;
use tracing::log;

#[derive(Debug, Clone)]
pub struct Database {
    pub connection: DatabaseConnection,
}

impl Database {
    pub async fn new(database_url: &str) -> Result<Self, DbErr> {
        let mut opt = ConnectOptions::new(database_url);
        opt.max_connections(100)
            .min_connections(5)
            .connect_timeout(Duration::from_secs(8))
            .acquire_timeout(Duration::from_secs(8))
            .idle_timeout(Duration::from_secs(8))
            .max_lifetime(Duration::from_secs(8))
            .sqlx_logging(true)
            .sqlx_logging_level(log::LevelFilter::Info);

        let connection = SeaDatabase::connect(opt).await?;
        
        tracing::info!("Database connected successfully");
        
        Ok(Self { connection })
    }

    pub fn get_connection(&self) -> &DatabaseConnection {
        &self.connection
    }

    pub async fn ping(&self) -> Result<(), DbErr> {
        self.connection.ping().await
    }

    pub async fn close(self) -> Result<(), DbErr> {
        self.connection.close().await
    }
}

// Health check for database
pub async fn health_check(db: &Database) -> bool {
    match db.ping().await {
        Ok(_) => {
            tracing::debug!("Database health check passed");
            true
        }
        Err(e) => {
            tracing::error!("Database health check failed: {}", e);
            false
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_database_connection() {
        // This test requires a running database
        // Skip if DATABASE_URL is not set
        if std::env::var("DATABASE_URL").is_err() {
            return;
        }
        
        let database_url = std::env::var("DATABASE_URL").unwrap();
        let db = Database::new(&database_url).await;
        assert!(db.is_ok());
        
        if let Ok(db) = db {
            assert!(health_check(&db).await);
        }
    }
}